package top.laoshuzi.common.mvp.presenter;

import android.support.annotation.Nullable;

import java.util.List;

import top.laoshuzi.common.mvp.factory.PresenterFactory;
import top.laoshuzi.common.mvp.view.View;


public final class PresenterLifecycleDelegate {

    @Nullable
    private PresenterFactory presenterFactory;
    @Nullable
    private List<? extends Presenter> presenters;


    public PresenterLifecycleDelegate(@Nullable PresenterFactory presenterFactory) {
        this.presenterFactory = presenterFactory;
    }


    public void create(View view) {

        if (presenterFactory == null) {
            return;
        }

        if (presenters == null) {
            presenters = presenterFactory.createPresenter();
        }

        if (presenters != null && !presenters.isEmpty()) {
//            PresenterStorage.INSTANCE.add(presenters);
            presenterFactory.bindPresenter(presenters);
            for (Presenter presenter : presenters) {
                presenter.create(view);
            }
        }

    }

    public void destroy(boolean isFinal) {
        if (presenters != null && !presenters.isEmpty() && isFinal) {
            for (Presenter presenter : presenters) {
                presenter.destroy();
            }
            presenters.clear();
            presenters = null;
        }
    }

    @Nullable
    public PresenterFactory getPresenterFactory() {
        return presenterFactory;
    }

    public void setPresenterFactory(@Nullable PresenterFactory presenterFactory) {
        this.presenterFactory = presenterFactory;
    }
}
